package com.gzist.security4.filter;

import com.gzist.security4.domain.User;
import com.gzist.security4.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 *  jwt授权过滤器
 *  @author: 黄泽建
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    /*
     * @description:
     *   进行过滤器配置
     * @author: 黄泽建
     * @date: 2024/5/30 16:13
     **/
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authentication");
        Claims claims = null;
        try {
            //当token为空的时候直接放行交由后面的过滤器进行处理
            if (token == null) {
                doFilter(request, response, filterChain);
                return;
            }
            // 校验token的同时将其用户信息取出
            claims = JWTUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        User user = new User();
        //在拿到正确的token之后将其用户信息取出然后封装存到用户实体中
        Long id = claims.get("id",Long.class);
        String username = claims.get("username",String.class);
        String nickname = claims.get("nickname",String.class);
        List<String> list = claims.get("perms",List.class);
        user.setId(id);
        user.setUsername(username);
        user.setNickname(nickname);
        user.setPerms(list);
        //拿到用户信息与权限信息后将其存储到authentication后并注入SecurityContactHolder中
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // !!!一定记得放行
        doFilter(request, response, filterChain);
    }
}
